//
//  RegistTableViewCell.h
//  CommunityNannyO2O
//
//  Created by apple on 15/8/13.
//  Copyright (c) 2015年 Apple. All rights reserved.
//

#import "RegistTableViewCell.h"
#import "APIAdress.h"
#import "MBProgressHUD+YC.h"
#import "MJExtension.h"
#import "AccountTool.h"
#import "UIViewController+Create.h"
#import "CustomTextField.h"
#import "AppConfig.h"
#import "RegistTableViewCell.h"
#import "QXNetWorkTool.h"
#import "VerificationModel.h"
#import "RegistModel.h"
#import "UserDataSingleton.h"
#import "CommFunc.h"

@interface RegistTableViewCell()<QXNetWorkToolDelegate>
{
    NSInteger timeCounter;
    NSTimer *timer;
}

@property (weak, nonatomic) IBOutlet CustomTextField  *phone;

@property (weak, nonatomic) IBOutlet CustomTextField  *verificationCode;

@property (weak, nonatomic) IBOutlet CustomTextField  *password;

@property (weak, nonatomic) IBOutlet CustomTextField  *passwordAgain;

@property (weak, nonatomic) IBOutlet UIButton *sendVerficationCode;

@property (weak, nonatomic) IBOutlet UIButton *regist;

@property (weak, nonatomic) IBOutlet UIButton *backBtn;

@property (weak, nonatomic) IBOutlet UIView *backView;

@property (strong, nonatomic) VerificationModel *code;

@end

@implementation RegistTableViewCell

+ (instancetype)cellWithTableView:(UITableView *)tableView
{
    static NSString *ID = @"RegistTableViewCell";
    RegistTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (cell == nil) {
        
        cell = [[[NSBundle mainBundle] loadNibNamed:ID owner:nil options:nil]firstObject];
        
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    }
    
    return cell;
}

-(void)awakeFromNib
{
    //叉号，一次性删除输入框中的内容
    [self.phone setClearButtonMode:UITextFieldViewModeWhileEditing];
    [self.verificationCode setClearButtonMode:UITextFieldViewModeWhileEditing];
    [self.password setClearButtonMode:UITextFieldViewModeWhileEditing];
    [self.passwordAgain setClearButtonMode:UITextFieldViewModeWhileEditing];
    
    //数字键盘
    self.phone.keyboardType = UIKeyboardTypeNumberPad;
    self.verificationCode.keyboardType = UIKeyboardTypeNumberPad;
    
    //编辑时清空
    self.phone.clearsOnBeginEditing = YES;
    self.verificationCode.clearsOnBeginEditing = YES;
    self.password.clearsOnBeginEditing = YES;
    self.password.clearsOnBeginEditing = YES;
    
    //placeholder字体、颜色
    [self.phone setFont:[UIFont fontWithName:@"Hiragino Sans GB" size:12]
                  Color:UIPlaceHolderDefaultColor];

    UIFont *font = [UIFont fontWithName:@"Hiragino Sans GB" size:14];
    [self.verificationCode setFont:font
                             Color:UIPlaceHolderDefaultColor];

    [self.password setFont:font
                     Color:UIPlaceHolderDefaultColor];

    [self.passwordAgain setFont:font
                          Color:UIPlaceHolderDefaultColor];
    
    //字体大小，verificationCode等其他文本框字体均为13
    self.phone.font = [UIFont fontWithName:DefaultFont size:13];
    
    //密码
    self.password.secureTextEntry = YES;
    self.passwordAgain.secureTextEntry = YES;
    
    
    //叉号
    UIButton *clearButton;
    clearButton = [self.phone valueForKey:@"_clearButton"];
    [clearButton setImage:[UIImage imageNamed:@"ico_login_del"]
                 forState:UIControlStateNormal];
    
    clearButton = [self.verificationCode valueForKey:@"_clearButton"];
    [clearButton setImage:[UIImage imageNamed:@"ico_login_del"]
                 forState:UIControlStateNormal];
    
    clearButton = [self.password valueForKey:@"_clearButton"];
    [clearButton setImage:[UIImage imageNamed:@"ico_login_del"]
                 forState:UIControlStateNormal];
    
    clearButton = [self.passwordAgain valueForKey:@"_clearButton"];
    [clearButton setImage:[UIImage imageNamed:@"ico_login_del"]
                 forState:UIControlStateNormal];
    
     [self.sendVerficationCode addTarget:self action:@selector(verficationCodeSender:) forControlEvents:UIControlEventTouchUpInside];
    
    self.regist.layer.cornerRadius = 16;
    self.regist.layer.masksToBounds = YES;
    [self.regist.layer setBorderWidth:1.0]; //边框宽度
    [self.regist.layer setBorderColor:UIColorRGBA(255, 255, 255, 1).CGColor];//边框颜色
    [self.regist addTarget:self action:@selector(registSender:) forControlEvents:UIControlEventTouchUpInside];
    
    //手势
    UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tap)];
    
    [self addGestureRecognizer:tapGestureRecognizer];
    
    //子view
    UIView *containView1 = [self viewWithTag: 1];
    
    UITapGestureRecognizer *tapGestureRecognizer1 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tap)];
    [containView1 addGestureRecognizer:tapGestureRecognizer1];
    
    //子view
    UIView *containView2 = [self viewWithTag: 2];
    
    UITapGestureRecognizer *tapGestureRecognizer2 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tap)];
    [containView2 addGestureRecognizer:tapGestureRecognizer2];
    
    //
    UIView *containView3 = [self viewWithTag: 3];
    
    UITapGestureRecognizer *tapGestureRecognizer3 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tap)];
    [containView3 addGestureRecognizer:tapGestureRecognizer3];
    
    UIView *containView4 = [self viewWithTag: 4];
    
    UITapGestureRecognizer *tapGestureRecognizer4 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tap)];
    [containView4 addGestureRecognizer:tapGestureRecognizer4];
    
    //back btn
    [self.backBtn addTarget:self action:@selector(backSender:) forControlEvents:UIControlEventTouchUpInside];
    
    //back view
    UITapGestureRecognizer *tapGestureRecognizerBack = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapBack)];
    [self.backView addGestureRecognizer:tapGestureRecognizerBack];
}

-(void)tap
{
    [self.phone resignFirstResponder];
    [self.verificationCode resignFirstResponder];
    [self.password resignFirstResponder];
    [self.passwordAgain resignFirstResponder];
}

- (BOOL)isCorrectPhone
{
    if ([self.phone.text isEqualToString:@""])
    {
        [MBProgressHUD showError:@"请输入手机号码" toView:self];
        return NO;
    }
    
    if ([CommFunc isPureInt:self.phone.text])
    {
        if(![CommFunc isValidateMobile:self.phone.text])
        {
            [MBProgressHUD showError:@"请正确输入手机号" toView:self];
            
            return NO;
        }
    }
    else
    {
        [MBProgressHUD showError:@"请正确输入手机号" toView:self];
        
        return NO;
    }
    
    return YES;
}

- (void)verficationCodeSender:(id)sender
{
    if ([self isCorrectPhone] == NO)
    {
        return;
    }
    
    QXNetWorkTool *QXnetWorkTool = [[QXNetWorkTool alloc]init];
    
    QXnetWorkTool.QXNetWorkDelegate = self;
    
    [QXnetWorkTool GetDataFromServerWithPostMethodandInterfaceName:VerificationCodeInterface andParameter:@[@{@"phone":_phone.text}] tag:1];
}

-(void)GetSuccessResponse:(id)Response andTag:(int)tag
{
    switch (tag)
    {
        case 1:
        {
            if (Response == nil)
                return;
            
            [MBProgressHUD showSuccess:@"获取验证码成功"];
            
            timeCounter = 61;//60秒倒计时
            
            timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeFireMethod) userInfo:nil repeats:YES];
            
            for (NSDictionary *dic in Response)
            {
                self.code = [VerificationModel VerificationWithDict:dic];
                break;
            }

            break;
        }
        case 2:
            for (NSDictionary *dic in Response)
            {
                RegistModel *model = [RegistModel RegistWithDict:dic];
                [UserDataSingleton shareInstance].user_id = model.user_id;
            }
            break;
    }
}

- (void)GetFailResponse:(id)Response andTag:(int)tag
{
    if (Response == nil)
        return;
    
    NSString *message = Response;
    
    switch (tag)
    {
        case 1:
            [MBProgressHUD showError:message];
            break;
        
        case 2:
            [MBProgressHUD showError:message];
            break;
    }
}

- (void)GetSuccessMessage:(id)message andTag:(int)tag
{
    NSString *mes = message;
    
    switch (tag)
    {
        case 2:
            [MBProgressHUD showSuccess:mes];
            
            if ([self.delegate respondsToSelector:@selector(registSuccess)]) {
                
                [self.delegate registSuccess];
            }
            
            break;
    }
}

-(void)timeFireMethod
{
    if (timeCounter < 0)
    {
        return;
    }
    
    timeCounter--;
    
    [self.sendVerficationCode setTitleColor:MIDIDefaultColor forState:UIControlStateNormal];
    
    self.sendVerficationCode.titleLabel.font =
    [UIFont fontWithName:DefaultFont size:9];
    
    [self.sendVerficationCode setTitle:[NSString stringWithFormat:@"重新发送(%ld)",(long)timeCounter] forState:UIControlStateNormal];
    
    self.sendVerficationCode.userInteractionEnabled = NO;
    
    if(timeCounter <= 0)
    {
        [timer invalidate];
        timer = nil;
        [self.sendVerficationCode setTitle:@"获取验证码" forState:UIControlStateNormal];
        self.sendVerficationCode.userInteractionEnabled = YES;
    }
}


- (void)registSender:(id)sender
{
    if ([self isCorrectPhone] == NO)
    {
        return;
    }
    
    if ([self.verificationCode.text isEqualToString:@""])
    {
        [MBProgressHUD showError:@"请输入验证码"];
        return;
    }
    
    if (![self.verificationCode.text isEqualToString:self.code.validate_num])
    {
        [MBProgressHUD showError:@"验证码错误"];
        return;
    }

    if (self.password.text.length <= 0
        || self.passwordAgain.text.length <= 0)
    {
        [MBProgressHUD showError:@"请输入密码"];
        return;
    }
    
    if (![self.password.text isEqualToString:self.passwordAgain.text])
    {
        [MBProgressHUD showError:@"请确保两次输入的密码一致"];
        return;
    }
    
    QXNetWorkTool *QXnetWorkTool = [[QXNetWorkTool alloc]init];
    
    QXnetWorkTool.QXNetWorkDelegate = self;
    
    [QXnetWorkTool GetDataFromServerWithPostMethodandInterfaceName:RegistInterface andParameter:
        @[@{@"login_name":_phone.text,
            @"pwd":self.password.text,
            @"sure_pwd":self.passwordAgain.text,
            @"code":self.verificationCode.text,
            @"cid":[[UserDataSingleton shareInstance] getGeTuiClientID]}] tag:2];
}

- (void)backSender:(id)sender
{
    if ([self.delegate respondsToSelector:@selector(back)]) {
        
        [self.delegate back];
    }
}

-(void)tapBack
{
    if ([self.delegate respondsToSelector:@selector(back)]) {
        
        [self.delegate back];
    }
}


@end




















